<template>
  <div class="student-stats">
    <div class="stats-summary">
      <span>平均分：{{ avgScore }}</span>
      <span>最高分：{{ maxScore }}</span>
      <span>最低分：{{ minScore }}</span>
      <span>总学分：{{ totalCredit }}</span>
    </div>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  scores: {
    type: Array,
    default: () => []
  }
})

const chartRef = ref(null)

const avgScore = computed(() => {
  if (!props.scores.length) return '-'
  const sum = props.scores.reduce((acc, cur) => acc + (cur.score || 0), 0)
  return (sum / props.scores.length).toFixed(2)
})
const maxScore = computed(() => {
  if (!props.scores.length) return '-'
  return Math.max(...props.scores.map(s => s.score || 0))
})
const minScore = computed(() => {
  if (!props.scores.length) return '-'
  return Math.min(...props.scores.map(s => s.score || 0))
})
const totalCredit = computed(() => {
  if (!props.scores.length) return '-'
  return props.scores.reduce((acc, cur) => acc + (cur.credit || 0), 0)
})

const renderChart = () => {
  if (!chartRef.value) return
  const chart = echarts.init(chartRef.value)
  chart.setOption({
    title: { text: '各课程成绩分布', left: 'center', top: 10, textStyle: { fontSize: 16 } },
    tooltip: {},
    xAxis: { type: 'category', data: props.scores.map(s => s.courseName) },
    yAxis: { type: 'value', min: 0, max: 100 },
    series: [{
      data: props.scores.map(s => s.score),
      type: 'bar',
      itemStyle: { color: '#409eff', borderRadius: [6,6,0,0] },
      barWidth: 32
    }]
  })
}

onMounted(() => {
  renderChart()
})
watch(() => props.scores, () => {
  renderChart()
})
</script>

<style scoped>
.student-stats {
  margin-bottom: 24px;
  background: #f8fafc;
  border-radius: 12px;
  padding: 18px 18px 10px 18px;
  box-shadow: 0 2px 8px 0 rgba(64,158,255,0.06);
}
.stats-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  font-size: 15px;
  margin-bottom: 12px;
  color: #333;
}
.chart {
  width: 100%;
  min-height: 260px;
  height: 300px;
}
</style> 